<?php
namespace Home\Model;

use Think\Model;

class ContentModel extends Model {
	
	/**
	 * 获得当前栏目文章列表
	 * @param $cate 栏目id
	 * @param $paginate 是否启用分页
	 * @param $p 当前页
	 * @return 获得子栏列表
	 */
	public function lists($cate=0, $paginate=false, $pageSize=10, $p=1) {
		if($cate && $category = M("Category")->find($cate)) {
			$model = $this->getModel($cate);
			$tableName = $this->getTableName($model['tag']);
			$model['modelName'] = $this->getModelName($model['tag']);
			$extModelName = $this->getExtTableName($tableName);
			$tableName = '__'.strtoupper($tableName).'__';
			$extModelName = '__'.strtoupper($extModelName).'__';
			$condition = array(
				"this0.customer" => $category['customer'],
				"this0.is_deleted" => 0,
				"this0.category" => $cate
			);
			$m = M()->table("$tableName this0")->join("LEFT JOIN $extModelName this1 on this0.id=this1.id")->where($condition);
			$new_m = clone $m;
			if($paginate){
				$m->limit($pageSize)->page($p);
				$contentCount = $new_m->count();
			}
			$contentLists = $m->select();
			return array("data"=>$contentLists, "count"=>$contentCount, "model" => $model);
		} else return array();
	}
	
	/**
	 * 获得内容详细
	 * @param unknown $cat 栏目ID 必须
	 * @param unknown $arc 文章ID	 必须
	 */
	public function detail($cate, $arc) {
		if($cate && $category = M("Category")->find($cate)) {
			$model = $this->getModel($cate);
			$tableName = $this->getTableName($model['tag']);
			$extModelName = $this->getExtTableName($tableName);
			$tableName = '__'.strtoupper($tableName).'__';
			$extModelName = '__'.strtoupper($extModelName).'__';
			$condition = array(
					"this0.customer" => $category['customer'],
					"this0.is_deleted" => 0,
					"this0.category" => $cate,
					"this0.id" => $arc,
			);
			$data = M()->table("$tableName this0")->join("LEFT JOIN $extModelName this1 on this0.id=this1.id")->where($condition)->find();
			return array('data'=>$data, 'model' => $model);
		} else return array();
	}
	
	// 获得模型表名
	public function getTableName($tag) {
		if(!empty($tag)){
			return "model_".strtolower($tag);
		}
		return 0;
	}
	
	// 获得模型名
	public function getModelName($tag) {
		if(!empty($tag)){
			return "Model".ucfirst(strtolower($tag));
		}
		return 0;
	}
	
	// 获得模型信息
	public function getModel($category) {
		$condition = array('_string' => "this0.model = this1.id and this0.type='list'",
				'this0.id' => $category);
		$model = M()->table("__CATEGORY__ this0,__MODEL__ this1")->where($condition)->field('this1.*')->find();
		return $model;
	}
	
	// 获得扩展表名
	public function getExtTableName($modelName) {
		if(!empty($modelName)){
			return $modelName."_config";
		}
		return 0;
	}
	
	public function realModel($cate) {
		$model = $this->getModel($cate);
		$modelName = $this->getModelName($model['tag']);
		return D($modelName);
	}
	
}